import { sqlLogger } from '@/common/logs4js/log4js.config';
import { ArgumentsHost, Catch, ExceptionFilter, Inject } from '@nestjs/common';
import { Request, Response } from 'express';
import { Logger } from 'nestjs-pino';
import { QueryFailedError, TypeORMError } from 'typeorm';

@Catch(TypeORMError)
export class TypeormFilter implements ExceptionFilter {
  constructor(@Inject(Logger) private logger: Logger) {}
  catch(exception: TypeORMError, host: ArgumentsHost) {
    console.log('typeorm.filter.ts');
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const request = ctx.getRequest<Request>();

    // 确定状态码和错误信息
    let code = 500;
    let message = exception.message;

    if (exception instanceof QueryFailedError) {
      code = exception.driverError.errno;
      if (code === 1062) {
        message = '唯一索引冲突';
      }
    }

    const errorInfo = {
      code: code,
      message: message,
      timestamp: new Date().toISOString(),
      path: request.url,
    };

    // 记录错误日志
    sqlLogger.error(errorInfo);

    // 返回标准化错误响应
    response.status(500).json(errorInfo);
  }
}
